import Cookie from 'js-cookie';
import { uuid } from './lang';

const iosBridge = window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.FNJSBridge;
const androidBridge = window.FNJSBridge;

const bind = (method, param, cb, { clear = true } = {}) => {
	const id = uuid('_bridge_');

	window[id] = (...args) => {
		/* eslint-disable */
		if (cb) {
			cb(...args);
		}
		/* eslint-enable */

		if (clear) {
			window[id] = null;
			try {
				delete window[id];
			} catch (e) {
				// do nothing
			}
		}
	};

	/* ios */
	if (iosBridge) {
		const msg = JSON.stringify({
			methodName: method,
			param: param || '',
			callback: id
		});
		iosBridge.postMessage(msg);
	/* android */
	} else if (androidBridge) {
		androidBridge.callHandler(method, param != null ? JSON.stringify(param) : '', id);
	/* 触屏 */
	} else {
		window[id]();
	}
};

const formatResp = (resp) => {
	if (resp) {
		if (resp.substring(0, 1) === '"') {
			resp = resp.substring(1, resp.length - 1);
		}
		/* eslint-disable */
		resp = (new Function(`return ${resp}`))();
		/* eslint-enable */
	} else {
		resp = {};
	}
	return resp;
};

const bridge = {
	iosAndroid () {
		return iosBridge ? true : false
	},
	postMessage (data = {}) {
		if (!data.methodName) {
			return;
		}
		bind(data.methodName, data.param, data.callback);
	},
	setTitle (title, callback) {
		bind('setTitle', { title }, callback);
	},
	setLoadingState (state, callback) {
		bind('setLoadingState', { state: !!state }, callback);
	},
	getCookies (callback = () => {}) {
		bind('getCookie', null, (cookies) => {
			// 通过桥接获取
			if (iosBridge || androidBridge) {
				cookies = formatResp(cookies);
			// 通过cookies获取
			} else {
				cookies = Cookie.get() || {};
			}

			callback(cookies);
		});
	},
	// landscape portrait
	setScreenOrientation (orientation, callback) {
		bind('setScreenOrientation', { orientation }, callback);
	},
	setAreaSelect (data, callback = () => {}) {
		bind('setAreaSelect', data, (resp) => {
			resp = formatResp(resp);
			callback(resp);
		}, {
			clear: false
		});
	}
}

export default bridge;
window.bridge = bridge;